const mongoose = require('mongoose');

/**
 * 食谱分类模型
 */
const recipeCategorySchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, '分类名称不能为空'],
      trim: true,
      unique: true
    },
    icon: {
      type: String,
      trim: true
    },
    description: {
      type: String,
      trim: true
    },
    order: {
      type: Number,
      default: 0
    },
    isActive: {
      type: Boolean,
      default: true
    },
    isDeleted: {
      type: Boolean,
      default: false
    }
  },
  {
    timestamps: true
  }
);

// 添加索引
recipeCategorySchema.index({ order: 1 });
recipeCategorySchema.index({ isActive: 1, isDeleted: 1 });

/**
 * 检查分类名称是否已被使用
 * @param {string} name - 分类名称
 * @param {ObjectId} [excludeCategoryId] - 排除的分类ID
 * @returns {Promise<boolean>}
 */
recipeCategorySchema.statics.isNameTaken = async function (name, excludeCategoryId) {
  const category = await this.findOne({ 
    name, 
    _id: { $ne: excludeCategoryId },
    isDeleted: false 
  });
  return !!category;
};

/**
 * @typedef RecipeCategory
 */
const RecipeCategory = mongoose.model('RecipeCategory', recipeCategorySchema);

module.exports = RecipeCategory; 